<template>
    <view>
		<canvas type="2d" id="getImageThemeColorCanvas" class="getImageThemeColorCanvas" width="3rpx"
				height="1.5rpx"></canvas>
        <view class="text" @click="setBackground">设置背景</view>
	</view>
</template>
<script>


	export default {
        methods:{
            setBackground(){
                const url = "https://img2.baidu.com/it/u=122597597,132720790&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500"
                setThemeBackground(url)
            },
            setThemeBackground(fileUrl) {
				const that = this;

				const canvasId = "getImageThemeColorCanvas"
				const query = wx.createSelectorQuery()

				query.select('#getImageThemeColorCanvas')
					.fields({
						node: true,
						size: true
					})
					.exec((res) => {
						const canvas = res[0].node
						const ctx = canvas.getContext('2d')
						let img = canvas.createImage();
						img.src = fileUrl;

						const dpr = wx.getSystemInfoSync().pixelRatio

						const imgWidth = res[0].width * dpr;
						const imgHeight = res[0].height * dpr;

						canvas.width = imgWidth
						canvas.height = imgHeight

						img.onload = (e) => {
							const respect = canvas.height / canvas.width

							ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
							ctx.scale(100, 100)
							const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

							const rgb = that.calcRGB(imageData.data, imgWidth, imgHeight)

							that.bgStyle = {
								"backgroundColor": rgb
							}
						};
					})
			},
            calcRGB(data, imgWidth, imgHeight) {
				var r = 1,
					g = 1,
					b = 1;
				// 取所有像素的平均值
				for (var row = 0; row < imgHeight; row++) {
					for (var col = 0; col < imgWidth; col++) {
						if (row == 0) {
							r += data[((imgWidth * row) + col)];
							g += data[((imgWidth * row) + col) + 1];
							b += data[((imgWidth * row) + col) + 2];
						} else {
							r += data[((imgWidth * row) + col) * 4];
							g += data[((imgWidth * row) + col) * 4 + 1];
							b += data[((imgWidth * row) + col) * 4 + 2];
						}
					}
				}
				// 求取平均值
				r /= (imgWidth * imgHeight);
				g /= (imgWidth * imgHeight);
				b /= (imgWidth * imgHeight);
				// 将最终的值取整
				r = Math.round(r);
				g = Math.round(g);
				b = Math.round(b);


				// onload 内
				const colorList = {}
				let i = 0;
				while (i < data.length) {
					const r = data[i];
					const g = data[i + 1];
					const b = data[i + 2];
					const a = data[i + 3];
					i = i + 4; // 最后 +4 比每次 i++ 快 10ms 左右性能
					const key = [r, g, b, a].join(',')
					key in colorList ? ++colorList[key] : (colorList[key] = 1)
				}
				// onload 内
				let arr = [];
				for (let key in colorList) {
					arr.push({
						rgba: `rgba(${key})`,
						num: colorList[key]
					})
				}
				arr = arr.sort((a, b) => b.num - a.num)

				return `rgba(${r},${g},${b},1)`
			}
        }
    }
</script>	
<style scoped>
	.getImageThemeColorCanvas {
			position: absolute;
			top: 60rpx;
			left: -1000rpx;
	}
</style>